package com.taotao.health.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.*;

public class demo02 {
    // Correct OpenAI API endpoint
    String chatEndpoint = "https://api.openai.com/v1/chat/completions";

    // Replace with your valid OpenAI API key
    String apiKey = "sk-009071728ffd4fb5aadb202d2ca5df31";

    List<Map<String, String>> dataList = new ArrayList<>();

    demo02() {
        // Initialize system role
        dataList.add(new HashMap<String, String>() {{
            put("role", "system");
            put("content", "2");
        }});
    }

    public String chat(String txt) {
        // Construct request parameters
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("model", "gpt-3.5-turbo");
        dataList.add(new HashMap<String, String>() {{
            put("role", "user");
            put("content", txt);
        }});
        paramMap.put("messages", dataList);

        try {
            // Send HTTP request
            String body = HttpRequest.post(chatEndpoint)
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute()
                    .body();

            // Print API response for debugging
            System.out.println("API Response: " + body);

            // Parse API response
            JSONObject jsonObject = JSON.parseObject(body);
            if (jsonObject.containsKey("error")) {
                throw new IllegalStateException(jsonObject.getJSONObject("error").getString("message"));
            }

            // Extract AI response
            JSONArray choices = jsonObject.getJSONArray("choices");
            JSONObject firstChoice = choices.getJSONObject(0);
            JSONObject message = firstChoice.getJSONObject("message");
            String res = message.getString("content");

            // Add AI response to conversation history
            dataList.add(new HashMap<String, String>() {{
                put("role", "assistant");
                put("content", res);
            }});

            return res;
        } catch (Exception e) {
            throw new IllegalStateException("API 调用失败: " + e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        demo02 c = new demo02();
        System.out.println("欢迎使用 ChatGPT 聊天机器人！");
        Scanner input = new Scanner(System.in);

        while (true) {
            System.out.print("我: ");
            String userInput = input.nextLine();
            if (userInput.equalsIgnoreCase("exit")) {
                System.out.println("聊天结束，再见！");
                break;
            }

            System.out.print("ChatGPT: ");
            try {
                String response = c.chat(userInput);
                System.out.println(response);
            } catch (Exception e) {
                System.err.println("出错: " + e.getMessage());
            }
        }
        input.close();
    }
}
